package com.example.gulimall.authserver.controller;

import com.alibaba.fastjson.TypeReference;
import com.example.common.constant.AuthServerConstant;
import com.example.common.exception.BizCodeEnum;
import com.example.common.utils.R;
import com.example.common.vo.MemberResponseVo;
import com.example.gulimall.authserver.feign.MemberFeignService;
import com.example.gulimall.authserver.vo.UserLoginVo;
import com.example.gulimall.authserver.vo.UserRegistVo;
import com.example.gulimall.authserver.feign.ThirdPartFeignService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {

//    @GetMapping("/login.html")
//    public String loginpage(){
//        return "login";
//    }
//
//    @GetMapping("/reg.html")
//    public String regpage(){
//        return "reg";
//    }

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private StringRedisTemplate template;

    @Autowired
    private MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone){

        String redisCode = template.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone);

        // 1. 接口防刷



        // 2.验证码多次校验
        if(!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if(System.currentTimeMillis() - l <= 60000){
                // 60秒内不可
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(),BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        String code = UUID.randomUUID().toString().substring(0, 5);
        String substring = code + "_" + System.currentTimeMillis();
        template.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,substring,10, TimeUnit.MINUTES);


        thirdPartFeignService.sendCode(phone,code);
        return R.ok();
    }

    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo,BindingResult result, RedirectAttributes redirectAttributes){

        if(result.hasErrors()){
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            //model.addAttribute("errors",errors);
            redirectAttributes.addFlashAttribute("errors",errors);
            System.out.println(errors.toString());
            //校验出错 直接转发代表会再次提交
            // session会在同一个域名下共享数据 下一次跳转取出数据后 就会自动删掉
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //校验验证码
        String code = vo.getCode();

        String s = template.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if(!StringUtils.isEmpty(s) && code.equals(s.split("_")[0])){
            template.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
            //调用远程服务
            R r = memberFeignService.regist(vo);
            if(r.getCode() == 0){
                System.out.println("进来啦！！");
                return "redirect:http://auth.gulimall.com/login.html";
            }else{
                System.out.println("报错了！！！");
                Map<String, String> errors = new HashMap<>();
                errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
                redirectAttributes.addFlashAttribute("errors",errors);
                System.out.println(errors.toString());
                //校验出错 直接转发代表会再次提交
                // session会在同一个域名下共享数据 下一次跳转取出数据后 就会自动删掉
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else{
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        // 路径转发默认是get模式 post会报错 所以一定要注意注意
    }


    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        //System.out.println(vo.toString());
        R login = memberFeignService.login(vo);
        if(login.getCode() == 0) {
            MemberResponseVo loginData = login.getData(new TypeReference<MemberResponseVo>(){});
            System.out.println(loginData);
            session.setAttribute(AuthServerConstant.LOGIN_USER, loginData);
            return "redirect:http://gulimall.com";
        }
        Map<String, String> errors = new HashMap<>();
        errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
        redirectAttributes.addFlashAttribute("errors",errors);
        return "redirect:http://auth.gulimall.com/login.html";
    }
}
